import { View, Text, ScrollView } from "@tarojs/components";
import { requestPayment, navigateTo } from "@tarojs/taro";
import {
  Tabs,
  Empty,
  Image,
  Button,
  Price,
  Dialog,
  InputNumber,
  ConfigProvider,
} from "@nutui/nutui-react-taro";
import { useState, useEffect, useContext } from "react";
import { getOpusList } from "@/api/distribution";
import {
  getOrderList,
  createOrder,
  getOrderInfo,
  submitPay,
  getSubjectList,
} from "@/api/pay";
import { orderList } from "@/api/distribution";
import { LoginContext } from "@/context/login-provider";
import dayjs from "dayjs";
import { orderStatus } from "@/hooks/getOrderStatus";
import Taro from "@tarojs/taro";

const Distribution = () => {
  const { userInfo } = useContext(LoginContext);
  const [active, setActive] = useState<number | string>(0);
  //激活码列表
  const [pageNo, setPageNo] = useState(1);
  const [total, setTotal] = useState(0);
  const [opusLoading, setOpusLoading] = useState(false);
  const [opusList, setOpusList] = useState<any[]>([]);
  const getList = async (isPage = false) => {
    setOpusLoading(true);
    Taro.showLoading();
    const res = await getOpusList({
      pageNo,
      pageSize: 10,
    });
    Taro.hideLoading();
    setOpusLoading(false);
    setOpusList(isPage ? [...opusList, ...res.data.list] : res.data.list);
    setTotal(res.data.total);
  };
  //激活码购买
  const [opusUid, setOpusUid] = useState<any>("");
  const [dialogVisible, setDialogVisible] = useState(false);
  const [count, setCount] = useState<any>(1);
  const [totalPrice, setTotalPrice] = useState<any>(0);
  const [skuId, setSkuId] = useState<any>("");
  const onsubmitPay = async () => {
    const res = await createOrder({
      terminal: 10,
      items: [{ skuId, count }],
      pointStatus: false,
      deliveryType: 3,
      from: undefined,
      extensionId: opusUid,
    });
    const result = await submitPay({
      channelCode: "wx_lite",
      channelExtras: { openid: userInfo?.openid },
      id: res?.data?.payOrderId,
    });
    const { timeStamp, nonceStr, packageValue, signType, paySign } = JSON.parse(
      result?.data?.displayContent
    );
    requestPayment({
      timeStamp,
      nonceStr,
      package: packageValue,
      signType,
      paySign,
      success: () => {
        setDialogVisible(false);
        navigateTo({
          url: `/pages/distribution-detail/index?id=${res?.data?.id}`,
        });
      },
    });
  };

  //购买记录
  const [recordList, setRecordList] = useState<any[]>([]);
  const getRecordList = async () => {
    setOpusLoading(true);
    Taro.showLoading();

    const res = await orderList({ type: 20 });
    Taro.hideLoading();
    setOpusLoading(false);
    setRecordList(res?.data?.list);
  };
  const getOrderPrice = async () => {
    const res = await getOrderInfo({
      deliveryType: 3,
      items: [
        {
          skuId,
          count,
        },
      ],
      pointStatus: false,
    });
    if (res?.data) {
      setSkuId(res?.data?.items[0]?.skuId);
      setTotalPrice(res?.data?.price?.totalPrice / 100);
    }
  };
  useEffect(() => {
    if (active === 0) {
      getList();
    } else if (active === 1) {
      setPageNo(1);
      getRecordList();
    }
  }, [active]);
  useEffect(() => {
    if (pageNo > 1) {
      getList(true);
    }
  }, [pageNo]);
  useEffect(() => {
    if (skuId && dialogVisible && count) {
      getOrderPrice();
    }
  }, [count, dialogVisible]);
  useEffect(() => {
    getSubjectList().then((res) => {
      setSkuId(res?.data?.list[0]?.skus[0]?.id);
    });
  }, []);
  return (
    <View className="bg-[#F5F5F5] p-3 box-border min-h-screen distribution">
      <Tabs value={active} onChange={setActive}>
        <Tabs.TabPane title="我的课程" className="!bg-transparent !p-0">
          <ScrollView
            className="h-[calc(100vh-68px)]"
            lowerThreshold={100}
            onScrollToLower={() => {
              if (opusList.length < total) {
                setPageNo(pageNo + 1);
              }
            }}
            scrollY
          >
            {opusList?.length > 0 ? (
              opusList?.map((item) => (
                <View
                  className="rounded-md p-2 bg-white mb-4 relative"
                  key={item.opusUid}
                >
                  <View
                    onClick={() => {
                      navigateTo({
                        url: `/pages/courseRedemption/index?dataid=${item.opusUid}&opusName=${item.opusName}`,
                      });
                    }}
                    className="flex justify-between items-center gap-4"
                  >
                    <Image
                      width={100}
                      height={100}
                      mode="aspectFit"
                      radius="16rpx"
                      src={item?.coverImage}
                    />
                    <View className="flex-1 flex flex-col justify-between font-normal">
                      <View className="text-[28rpx] text-[#222] line-clamp-2 flex-1">
                        {item?.opusName}
                      </View>
                      <View className="text-[#fa2c19] mt-2 mb-1">
                        <Text className="text-[24rpx] font-semibold mr-[5rpx]">
                          ¥
                        </Text>
                        <Text className="text-[34rpx] font-semibold">
                          {item.price?.toFixed(2)}
                        </Text>
                        <Text className="text-[24rpx] ml-[10rpx]">销售价</Text>
                      </View>
                      <View className="text-[26rpx] text-[#999]">
                        {dayjs(item?.createTime).format("YYYY-MM-DD HH:mm:ss")}
                      </View>
                    </View>
                  </View>
                  <View className="flex justify-end gap-2">
                    <Button
                      onClick={() => {
                        setOpusUid(item.opusUid);
                        setDialogVisible(true);
                      }}
                      size="small"
                      type="primary"
                    >
                      激活购买
                    </Button>
                    <Button
                      onClick={() =>
                        navigateTo({
                          url: `/pages/course-detail/index?opusUid=${item.opusUid}`,
                        })
                      }
                      size="small"
                    >
                      课程详情
                    </Button>
                  </View>
                </View>
              ))
            ) : !opusLoading ? (
              <Empty
                description={
                  <View className="text-sm text-gray-500 mt-4">暂无数据</View>
                }
                image={require("../../assets/course/wu.svg")}
              />
            ) : null}
          </ScrollView>
        </Tabs.TabPane>
        <Tabs.TabPane title="购买记录" className="!bg-transparent !p-0">
          <ScrollView scrollY className="h-[calc(100vh-68px)]">
            {recordList?.length > 0 ? (
              recordList?.map((item) => (
                <View key={item.id} className="bg-white p-4 rounded-md mb-4">
                  <View
                    className="relative flex gap-4"
                    onClick={() => {
                      navigateTo({
                        url: `/pages/distribution-detail/index?id=${item.id}`,
                      });
                    }}
                  >
                    <Image
                      width={100}
                      height={100}
                      radius="16rpx"
                      mode="aspectFit"
                      src={item.picUrl}
                    />
                    <View className="flex-1">
                      <View className="flex justify-between items-start">
                        <View className="text-[28rpx] text-[#222] line-clamp-2 flex-1">
                          {item?.name}
                        </View>
                        <View className="text-[28rpx] text-[#EF4D29]">
                          {orderStatus(item?.status)}
                        </View>
                      </View>
                      <View className="flex justify-between items-end mt-2 mb-1">
                        <View className="text-[#fa2c19]">
                          <Text className="text-[24rpx] font-semibold mr-[5rpx]">
                            ¥
                          </Text>
                          <Text className="text-[34rpx] font-semibold">
                            {item?.payPrice / 100}
                          </Text>
                        </View>
                        <View className="text-[26rpx] text-[#999]">
                          {item?.codeCountRespVO?.usedCount || 0}/
                          {item?.codeCountRespVO?.totalCount || 0}
                        </View>
                      </View>
                      <View className="text-[26rpx] text-[#999]">
                        {dayjs(item?.createTime).format("YYYY-MM-DD HH:mm:ss")}
                      </View>
                    </View>
                  </View>
                  <View className="flex justify-end">
                    <Button
                      size="small"
                      onClick={() => {
                        navigateTo({
                          url: `/pages/distribution-detail/index?id=${item.id}`,
                        });
                      }}
                      type="primary"
                    >
                      查看兑换码
                    </Button>
                  </View>
                </View>
              ))
            ) : !opusLoading ? (
              <Empty
                description={
                  <View className="text-sm text-gray-500 mt-4">暂无数据</View>
                }
                image={require("../../assets/course/wu.svg")}
              />
            ) : null}
          </ScrollView>
        </Tabs.TabPane>
        <Tabs.TabPane title="购买兑换码" className="!bg-transparent !p-0">
          <View className="w-full h-[100px] flex flex-col justify-center items-center gap-2">
            <Button
              onClick={() => {
                setOpusUid("ONLY_CODE");
                setDialogVisible(true);
              }}
              type="primary"
              size="large"
            >
              购买通用兑换码
            </Button>
            <Text className="text-xs text-gray-500">
              购买后可在PC上进行课程的绑定后才能兑换使用
            </Text>
          </View>
        </Tabs.TabPane>
      </Tabs>
      <Dialog
        visible={dialogVisible}
        onCancel={() => {
          setDialogVisible(false);
          setCount(1);
          setTotalPrice(0);
        }}
        title="购买兑换码"
        onConfirm={onsubmitPay}
      >
        <View className="flex items-center gap-2">
          <Text>购买数量：</Text>
          <View className="flex-1">
            <ConfigProvider
              theme={{
                nutuiInputnumberButtonWidth: "24px",
                nutuiInputnumberButtonHeight: "24px",
                nutuiInputnumberButtonBackgroundColor: `#f4f4f4`,
                nutuiInputnumberInputBackgroundColor: "#fff",
                nutuiInputnumberInputMargin: "0 2px",
              }}
            >
              <InputNumber
                value={count}
                onChange={setCount}
                onBlur={() => {
                  if (!count) {
                    setCount(1);
                  }
                }}
                min={1}
                max={9999}
              />
            </ConfigProvider>
          </View>
        </View>
        <View className="flex items-center gap-2 mt-4">
          <Text className="w-[70px]">总价：</Text>
          <View className="flex-1">
            <Price price={totalPrice} size="normal" thousands />
          </View>
        </View>
      </Dialog>
    </View>
  );
};

export default Distribution;
